import Vue from "vue";
import VueRouter from 'vue-router'
import {dbSet} from "@/libs/db";
import cookies from "@/libs/cookies";

export default {
    namespaced: true,
    state: {
        // 用户信息
        user: undefined,
        menu: undefined,
        role: undefined
    },
    mutations: {
        setUser(state, data) {
            state.user = data
        },
        setMenu(state, data) {
            state.menu = data
        },
        setRole(state, data) {
            state.role = data
        },
    },
    actions: {
        /**
         * @description 从数据库取用户数据
         * @param {Object} context
         */
        async load({commit, state, dispatch}, that) {
            try {
                if (state.user == undefined) {
                    let userInfo = cookies.get("userInfo");
                    userInfo = JSON.parse(userInfo)
                    await commit('setUser', userInfo)
                    Vue.prototype.$user = userInfo;
                }
                if (state.menu == undefined) {
                    await dispatch('store/user/getMenuList', that, {root: true})
                }
                if (state.role == undefined) {
                    await dispatch('store/user/getAreaList', that, {root: true})
                }
                return {
                    user:state.user,
                    menu:state.menu,
                    role:state.role
                };
            } catch (e) {
                // 结束
                return Promise.reject(e)
            }
        },
        /**
         * @description 登录
         * @param {Object} vuex context
         * @param {Object} payload username {String} 用户账号
         * @param {Object} payload password {String} 密码
         * @param {Object} payload route {Object} 登录成功后定向的路由对象 任何 vue-router 支持的格式
         */
        async userLogin({commit, dispatch}, {username = '', password = '', that, to = '/index'} = {}) {
            try {
                let result = await dispatch('store/user/getToken', {
                    username: username,
                    password: password,
                    that: that
                }, {root: true})
                console.log(result)
                if (result===false) {
                    return false;
                }
                result = await dispatch('getUserInfo', {username: username, password: password, that: that});
                if (result===false) {
                    return false;
                }
                await dispatch('store/user/getMenuList', that, {root: true})
                await dispatch('store/user/getAreaList', that, {root: true})

            } catch (e) {
                // 结束
                return Promise.reject(e)
            }
        },
        async getUserInfo({commit, state, dispatch}, {username, password, that}) {
            return await that.$api.login({username: username, password: password}).then((res) => {
                if (res.data.code == 0) {
                    let userInfo = res.data.data;
                    delete userInfo.password;
                    cookies.set("userInfo", userInfo);
                    Vue.prototype.$user = userInfo;
                    commit('setUser', userInfo)
                    return true;
                } else {
                    that.$message.info(res.data.errorMessage);
                    return false;
                }
            });
        },
        async getToken({state, dispatch}, {username, password, that}) {
           return await that.$api.getToken({username: username, password: password}).then(res => {
                console.log(res.data)
                if (res.data.code == 200) {
                    dbSet({dbName: "token", value: ''});
                    dbSet({dbName: "token", value: res.data.data.token});
                } else {
                    that.$message.info(res.data.errorMessage);
                    return false
                }
            })
        },
        async getMenuList({commit, state, dispatch}, that) {
            return await that.$api.findMenuByUserId(state.user.id).then((res) => {
                if(res.data.code == 0){
                    if (res.data.data && res.data.data.length != 0) {
                        let menuMap = new Map();
                        res.data.data.forEach((item) => {
                            menuMap.set(item.menuUrl, item.menuUrl);
                        });
                        commit('setMenu', menuMap)
                        Vue.prototype.$menu = new Map();
                        Vue.prototype.$menu = menuMap;
                        return menuMap
                        //that.$store.commit("store/page/setMenuLists", menuMap);
                    }else {
                        Vue.prototype.$menu = new Map;
                    }
                }else {
                    that.$message.warning(res.data.data)
                }
            });
        },
        async getAreaList({commit, state, dispatch}, that) {
            return await that.$api.AreaFindAreasByUserId(state.user.id).then((res) => {
                console.log(res.data)
                if (res.data.data.length != 0) {
                    console.log(res.data.data);
                    cookies.set("role", {
                        id: res.data.data[0].id,
                        name: res.data.data[0].name,
                    });
                    commit('setRole', res.data.data[0])
                    Vue.prototype.$role = res.data.data[0];
                    return res.data.data[0];
                }
            });
        },
    }
}
